package protocol

import (
	"net"

	"gitee.com/zatto/mcenter/common/logger"
	"gitee.com/zatto/mcenter/conf"
	"gitee.com/zatto/mcenter/protocol/auth"
	"github.com/infraboard/mcube/app"
	"github.com/infraboard/mcube/grpc/middleware/recovery"
	"google.golang.org/grpc"
)

type GRPCService struct {
	svc *grpc.Server
	c   *conf.Config
}

func NewGRPCService() *GRPCService {
	rc := recovery.NewInterceptor(recovery.NewZapRecoveryHandler())
	grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(
		rc.UnaryServerInterceptor(),
		auth.NewGrpcAuther().AuthFunc,
	))

	return &GRPCService{
		svc: grpcServer,
		c:   conf.C(),
	}
}

func (s *GRPCService) Start() {
	// 加载所有grpc服务
	app.LoadGrpcApp(s.svc)

	// 启动tcp监听
	listen, err := net.Listen("tcp", s.c.App.GRPC.Addr())
	if err != nil {
		logger.L().Debug().Msgf("Listen grpc tcp conn err, %s", err)
		return
	}

	// 启动grpc服务
	logger.L().Info().Msgf("GRPC 服务地址: %s", s.c.App.GRPC.Addr())
	if err := s.svc.Serve(listen); err != nil {
		if err == grpc.ErrServerStopped {
			logger.L().Info().Msg("service is stopped")
		}
		logger.L().Error().Msgf("start grpc sercice error, %s", err.Error())
		return
	}

}

func (s *GRPCService) Stop() error {
	s.svc.GracefulStop()
	return nil
}
